//
//  TRoadLoadingHandler.m
//  TRoad2
//
//  Created by ZhangYanhua on 15/9/14.
//  Copyright (c) 2015年 Mach. All rights reserved.
//

#import "TRoadLoadingHandler.h"

@interface TRoadLoadingHandler()

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation TRoadLoadingHandler

+ (TRoadLoadingHandler *)loadingHandlerWithTableView:(UITableView *)tableView
                                 pullRefreshDelegate:(id<TRoadPullRefreshProtocol>)delegate
{
    TRoadLoadingHandler *handler = [[TRoadLoadingHandler alloc] init];
    handler.tableView = tableView;
    handler.refreshDelegate = delegate;

    return handler;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.loadMoreView.hidden = YES;

    if (self.isLoading || self.isMoreLoading) {
        // Update the content inset, good for section headers
        if(self.isMoreLoading)
        {
            self.loadMoreView.hidden = NO;
            UIEdgeInsets loadingInset = self.tableView.contentInset;
            loadingInset.bottom = _originBottomInset + self.loadMoreView.viewHeight;
            self.tableView.contentInset = loadingInset;
        }
    }
    else if(scrollView.contentSize.height >= scrollView.bounds.size.height - scrollView.contentInset.top - _originBottomInset && (scrollView.contentOffset.y+scrollView.bounds.size.height - _originBottomInset)>scrollView.contentSize.height) {
        
        self.loadMoreView.hidden = !self.enableMore;
        
        if(self.enableMore) {
            [self p_addPullToMoreHeader];
            
            [UIView beginAnimations:nil context:NULL];
            if ([self p_hasMoreContent]) {
                if (scrollView.contentOffset.y > (scrollView.contentSize.height + self.loadMoreView.frame.size.height - scrollView.bounds.size.height + _originBottomInset)) {
                    [self.loadMoreView releaseToLoadMore];
                } else {
                    [self.loadMoreView pullToLoadMore];
                }
            } else {
                [self.loadMoreView showNoMoreContent];
            }
            [UIView commitAnimations];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.isLoading || self.isMoreLoading) return;
    
    if(scrollView.contentSize.height >= scrollView.bounds.size.height  - scrollView.contentInset.top - _originBottomInset && (scrollView.contentOffset.y+scrollView.bounds.size.height - _originBottomInset)>scrollView.contentSize.height + self.loadMoreView.viewHeight){
        if(self.enableMore == YES)
            [self startMoreLoading];
    }
}

-(void)startLoadingProgrammatically {
    if (self.isLoading || !self.enableRefresh) {
        return;
    }
    
    [self.TRDRefreshControl beginRefreshing];
    [self startLoading];
}
//add by eric end


- (void)startLoading {
    if (!self.isLoading && !self.isMoreLoading) {
        self.isLoading = YES;
        
        if (self.enableRefresh && [self.refreshDelegate respondsToSelector:@selector(doLoadingWithLoadingView:)]) {
            [self.refreshDelegate doLoadingWithLoadingView:nil];
        } else {
            [self stopLoading];
        }
    }
}

- (void)stopLoading {
    self.isLoading = NO;
    
    //hide the more header
    self.isMoreLoading = NO;
    
    [self.loadMoreView pullToLoadMore];
    
    // Hide the header
    [self.TRDRefreshControl endRefreshing];
}

- (void)startMoreLoading {
    self.isMoreLoading = YES;
    BOOL hasMore = [self p_hasMoreContent];
    
    UIEdgeInsets loadingInset = self.tableView.contentInset;
    loadingInset.bottom =  self.loadMoreView.viewHeight + _originBottomInset;
    CGPoint contentOffset = self.tableView.contentOffset;
    
    [UIView animateWithDuration:0.3
                          delay:0.0
                        options: UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.tableView.contentInset = loadingInset;
                         self.tableView.contentOffset = contentOffset;
                         
                         if (hasMore) {
                             [self.loadMoreView startMoreLoading];
                         } else {
                             [self.loadMoreView showNoMoreContent];
                         }
                     }
                     completion:^(BOOL finished){
                         if (hasMore) {
                             [self performSelector:@selector(p_doRealMoreLoading) withObject:nil afterDelay:0.1f];
                         } else {
                             [self performSelector:@selector(stopMoreLoading) withObject:nil afterDelay:0.1f];
                         }
                     }];
}

- (void)p_doRealMoreLoading
{
    if ([self.refreshDelegate respondsToSelector:@selector(doMoreLoading)]) {
        [self.refreshDelegate doMoreLoading];
    } else {
        NSAssert(NO, @"支持加载更多的ViewController必须实现more方法");
        [self performSelector:@selector(stopMoreLoading) withObject:nil afterDelay:1.0f];
    }
}

- (void)stopMoreLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    UIEdgeInsets loadingInset = self.tableView.contentInset;
    loadingInset.bottom = _originBottomInset;
    self.tableView.contentInset = loadingInset;
}

- (void)stopMoreLoading
{
    self.isMoreLoading = NO;
    BOOL hasMore = [self p_hasMoreContent];
    
    if (hasMore) {
        [self.loadMoreView stopMoreLoading];
    } else {
        [self.loadMoreView showNoMoreContent];
    }
    
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         UIEdgeInsets loadingInset = self.tableView.contentInset;
                         if (hasMore) {
                             loadingInset.bottom = _originBottomInset + self.loadMoreView.frame.size.height;
                         } else {
                             loadingInset.bottom = _originBottomInset;
                         }
                         self.tableView.contentInset = loadingInset;
                     }completion:^(BOOL finished) {
                         UIEdgeInsets loadingInset = self.tableView.contentInset;
                         loadingInset.bottom = _originBottomInset;
                         self.tableView.contentInset = loadingInset;
                         
                         self.loadMoreView.hidden = YES;
                     }];
}

#pragma mark -
#pragma mark private methods

- (BOOL)p_hasMoreContent
{
    BOOL canRespondsHasMoreContent = [self.refreshDelegate respondsToSelector:@selector(currentPageHasMoreContent)];
    NSAssert(canRespondsHasMoreContent, @"支持加载更多的ViewController必须实现currentPageHasMoreContent方法");
    BOOL hasMore = (canRespondsHasMoreContent && [self.refreshDelegate currentPageHasMoreContent]);
    return hasMore;
}

- (void)p_addPullToMoreHeader
{
    if(!self.enableMore)
        return;
    
    CGFloat startY = self.tableView.contentSize.height;
    
    if(self.loadMoreView == nil){
        self.loadMoreView = [TRoadMoreFooterView defaultMoreViewForTRoad];
    }
    
    [self.loadMoreView removeFromSuperview];
    [self.tableView addSubview:self.loadMoreView];
    
    CGRect frame = CGRectMake(0.0f, startY, self.tableView.frame.size.width, self.loadMoreView.viewHeight);
    self.loadMoreView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.loadMoreView.frame = frame;
    self.loadMoreView.hidden = NO;
}

#pragma mark -
#pragma mark setters and getters and private methods

- (void)setEnableMore:(BOOL)enableMore
{
    _enableMore = enableMore;
    if (!enableMore) {
        [self.loadMoreView removeFromSuperview];
    }
}

@end
